package resolver

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"fmt"
	"net"
	"strconv"
	"strings"

	"github.com/k8gb-io/k8gb/controllers/utils"
)

type EdgeDNSType string

const (
	// DNSTypeNoEdgeDNS is default DNSType. Is used during integration testing when no edgeDNS provider exists
	DNSTypeNoEdgeDNS EdgeDNSType = "NoEdgeDNS"
	// DNSTypeInfoblox type
	DNSTypeInfoblox EdgeDNSType = "Infoblox"
	// DNSTypeRoute53 type
	DNSTypeExternal EdgeDNSType = "ExtDNS"
	// DNSTypeMultipleProviders type
	DNSTypeMultipleProviders EdgeDNSType = "MultipleProviders"
)

func (c *Config) getEdgeDNSType() (EdgeDNSType, []EdgeDNSType) {
	recognized := make([]EdgeDNSType, 0)
	if c.ExtDNSEnabledRaw {
		recognized = append(recognized, DNSTypeExternal)
	}
	if len(c.Infoblox.Host) != 0 {
		recognized = append(recognized, DNSTypeInfoblox)
	}
	switch len(recognized) {
	case 0:
		return DNSTypeNoEdgeDNS, recognized
	case 1:
		return recognized[0], recognized
	}
	return DNSTypeMultipleProviders, recognized
}

func (c *Config) parseParentZoneDNSServers() (r []utils.DNSServer) {
	r = []utils.DNSServer{}
	var host, portStr string
	var err error
	if len(c.ParentZoneDNSServersRaw) == 0 {
		c.ParentZoneDNSServersRaw = []string{fmt.Sprintf("%s:%v", c.FallbackEdgeDNSServerNameRaw, c.FallbackEdgeDNSServerPortRaw)}
	}
	for _, chunk := range c.ParentZoneDNSServersRaw {
		chunk = strings.TrimSpace(chunk)
		switch strings.Count(chunk, ":") {
		case 0: // ipv4 or domain w/o port
			host = chunk
			portStr = "53"
		case 1: // ipv4 or domain w/ port
			host, portStr, err = net.SplitHostPort(chunk)
			if err != nil {
				continue
			}
		default: // ipv6 or http://foo:bar
			// not supported
			continue
		}
		var port int
		port, err = strconv.Atoi(portStr)
		if err != nil {
			port = 53
		}
		if host != "" {
			r = append(r, utils.DNSServer{
				Host: host,
				Port: port,
			})
		}
	}
	return r
}
